<?php
/*
 module:		发布管理
 create_time:	2022-03-09 16:30:59
 author:	陕西格创
 contact:		
*/

namespace app\api\controller;

use app\api\model\ZhChatLog;
use app\api\service\ZhMatchmakerMeetService;
use app\api\model\ZhAuthentication as ZhAuthenticationModel;
use think\facade\Db;
use app\api\model\ZhChat ;
use app\api\model\Member as MemberModel;
use app\api\model\ZhMatchmakerMeet as ZhMatchmakerMeetModel;
use utils\wechart\TemplateService;

class ZhMatchmakerMeet extends Common
{


    function index()
    {
        $m_id = intval($this->request->get('m_id'));
        $a_id = intval($this->request->get('a_id'));
        $type = intval($this->request->get('type',1));//1待开始  2已过期
        $limit = $this->request->get('limit', 20, 'intval');
        $page = $this->request->get('page', 1, 'intval');
        $where = [];
        if ($a_id > 0) {
            $where['o.a_id'] = $a_id;
        }
        if ($m_id > 0) {
            $where['o.m_id'] = $m_id;
        }
        if ($type == 1) {
            $where['o.meet_time'] = ['>', time()];
        } elseif ($type == 2) {
            $where['o.meet_time'] = ['<', time()];
        }
        $res = ZhMatchmakerMeetService::indexList(formatWhere($where), $limit, $page);
        foreach ($res['list'] as &$v) {
            $v['createtime'] = date('Y-m-d H:i:s', $v['createtime']);
            $v["meet_time"]=date("Y-m-d H:i:s",$v["meet_time"]);

        }
        return $this->ajaxReturn($this->successCode, '返回成功', $res);
    }
    //定时通知红娘
    function notice(){
        $temp_service=new TemplateService();
        $end_time=strtotime(date("Y-m-d 23:59:59"));
        $start_time=strtotime(date("Y-m-d 00:00:00"));

        $where=[];
        $where[]=["meet_time",'<=',$end_time];//小于当天时间
        $where[]=["meet_time",'>=',$start_time];//小于当天时间
        $where[]=["is_notice","=",0];
        $meet_list=\app\api\model\ZhMatchmakerMeet::where($where)->select()->toArray();
        if(count($meet_list)==0){
            echo "暂时没有当日邀约";
        }
        file_put_contents('notice_data.txt', "\n 获取到的meetlist:".json_encode($meet_list), FILE_APPEND);
        foreach ($meet_list as $met){
            $mid=intval($met["m_id"]);
            $id=intval($met["id"]);
            $matchmaker=\app\api\model\ZhMatchmaker::find($mid);
            $u_id=intval($matchmaker["u_id"]);
            $member=\app\api\model\Member::find($u_id);
            $open_id=$member["openid"];
            //循环给红娘发送模板消息
            $data=[];
            $data['template_id']="C8C8K35nyJzXTTrvrOfqWfa4Q0bPNgYSjmi7_bPkq3w";
            $data["openid"]=$open_id;
            $data["data"]=[
                "thing5"   => $matchmaker["name"],
                "time4"   => date("Y年m月d日",intval($met["meet_time"])),
                "thing10"   => $met["meet_address"],
                "thing3"   => "您有一个邀约，请前往",
            ];
            $res=$temp_service->sendSubscribeMessage($data);
            echo  $id." 发送订阅消息： ";
            print_r($res);
            file_put_contents('notice_data.txt', "\n 发起订阅接口， 返回参数 : ".json_encode($res),FILE_APPEND);
            if(key_exists("errcode",$res)){
                if($res["errcode"]==0){
                    //发送成功，修改meet表数据的is_notice=1
                    $m_res=\app\api\model\ZhMatchmakerMeet::update(["is_notice"=>1],["id"=>$met["id"]]);
                    echo "发送成功，修改is_notice";
                    print_r($m_res);
                    file_put_contents('notice_data.txt', "\n 设置is_notice: ".json_encode($m_res), FILE_APPEND);
                }else{
                    file_put_contents('notice_data.txt', "\n errcode!=0: ".json_encode($res), FILE_APPEND);
                    echo "发送失败 ";
                    print_r($res);
                }
            }else{
                file_put_contents('notice_data.txt', "\n 发起订阅接口，未返回errcode参数 : ".json_encode($res), FILE_APPEND);
                echo "发送失败 ";
                print_r($res);
            }


        }

    }
    function send_msg(){
        $temp_service=new TemplateService();
        //lwx oO_Sz68NYWAjt63SENKnqfiV0SRA
        //fu oO_Sz68xW8QVb5kzd54Xev2SMyes
        $open_id="oO_Sz68xW8QVb5kzd54Xev2SMyes";
        $data=[];
        $data['template_id']="C8C8K35nyJzXTTrvrOfqWfa4Q0bPNgYSjmi7_bPkq3w";
        $data["openid"]=$open_id;
        $data["data"]=[
            "thing5"   => "测试红娘111",
            "time4"   => date("Y年m月d日"),
            "thing10"   => "江南大道500号",
            "thing3"   => "您有一个邀约，请前往",
        ];
        $res=$temp_service->sendSubscribeMessage($data);
        if(key_exists("errcode",$res)){
            if($res["errcode"]==0){
                echo "发送成功啦";
            }
        }
        print_r($res);

    }

    function view()
    {
        $id=$this->request->get('id');
        if($id<=0){
            return $this->ajaxReturn($this->errorCode, '请传正确id');
        }
        $meet=ZhMatchmakerMeetModel::find($id);
        if(!$meet){
            return $this->ajaxReturn($this->errorCode, '邀约不存在，请传正确id');
        }
        $wxapp_id=$this->request->get('wxapp_id');
        $data['id'] =$id;
        $sql = 'select o.id,o.meet_time,o.meet_address,o.m_id,o.a_id,o.status, o.memo,o.createtime,o.nick_name,gc_zh_matchmaker.name  m_name,gc_zh_matchmaker.phone 
                from gc_zh_matchmaker_meet   as o  
                left join gc_zh_matchmaker  on o.m_id=gc_zh_matchmaker.matchmaker_id
                where o.id = '.$id.' limit 1';
        $info = Db::connect('mysql')->query($sql)[0];
        $info["createtime"]=date("Y-m-d H:i:s",$info["createtime"]);
        $info["meet_time"]=date("Y-m-d H:i:s",$info["meet_time"]);
        //判断是否已读 is_read=0
        if($info["is_read"]==0){
            //修改已读状态
            $data['updatetime'] =time();
            $res=ZhMatchmakerMeetModel::where(["id"=>$id])->update(["is_read"=>1]);
            if($res){
                //发送通知
                $matchmaker_meet=ZhMatchmakerMeetModel::find($id);
                $matchmaker=\app\api\model\ZhMatchmaker::where("matchmaker_id",$matchmaker_meet["m_id"])->find();
                //发起通知
                $notice["wxapp_id"]=$wxapp_id;
                $notice["u_id"]=0;//发送人id
                $notice['s_id'] =$matchmaker["u_id"];//接收人
                $notice['create_time'] =date("Y-m-d H:i:s");
                $notice['status'] =1;
                $c_id = ZhChat::insertGetId($notice);
                if($c_id) {
                    $content = "佳人/家长已查看您在" . date("Y-m-d H:i:s", $matchmaker_meet["createtime"]) . "发起的“线下相亲邀请”";
                    $log["wxapp_id"] = $wxapp_id;
                    $log["chat_id"] = $c_id;
                    $log["type"] = "text";
                    $log["content"] = $content;
                    $log["add_time"] = date("Y-m-d H:i:s");
                    $log["u_id"] = $matchmaker["u_id"];
                    $log["is_read"] = 0;
                    $log["record_time"] = date("H:i", time());
                    $c_log_id = ZhChatLog::insertGetId($log);
                }
            }

        }
        return $this->ajaxReturn($this->successCode, '返回成功', $info ?: '');
    }

    //红娘发起邀约见面
    function add()
    {
        $m_id = $this->request->post('m_id');
        $meet_time= $this->request->post('meet_time');
        $meet_address= $this->request->post('meet_address');
        $memo= $this->request->post('memo');
        $matchmaker=\app\api\model\ZhMatchmaker::where(["matchmaker_id"=>$m_id])->find();
        $nick_name = $this->request->post('nick_name','');
        if(!$matchmaker){
            return $this->ajaxReturn($this->errorCode, "m_id：".$m_id."  红娘不存在");
        }
        if(!$meet_time){
            return $this->ajaxReturn($this->errorCode, "见面时间不可为空");
        }
        if(!$meet_address){
            return $this->ajaxReturn($this->errorCode, "见面地点不可为空");
        }
        $data['m_id'] =$m_id;
        $data['nick_name'] =$nick_name;
        $data['meet_time'] =strtotime($meet_time);
        $data['meet_address']=$meet_address;
        $data['memo'] =$memo;
        $data['status']            = 0;
        $data['createtime'] = time();
        $meet_id              = ZhMatchmakerMeetModel::insertGetId($data);
        return $this->ajaxReturn($this->successCode, '操作成功', ["meet_id"=>$meet_id]);
    }
    //佳人同意谢媒费
    function update(){
        $id = $this->request->post('id');
        $a_id = $this->request->post('a_id');
        $status = $this->request->post('status');
        $wxapp_id = $this->request->post('wxapp_id');
        $matchmaker_meet=ZhMatchmakerMeetModel::find($id);
        $matchmaker=\app\api\model\ZhMatchmaker::where("matchmaker_id",$matchmaker_meet["m_id"])->find();
        if(!$matchmaker_meet){
            return $this->ajaxReturn($this->errorCode, "数据不存在，请传正确id");
        }


        if(!in_array($status,[1,2])){
            return $this->ajaxReturn($this->errorCode, "status参数不正确");
        }
        $data['a_id'] =$a_id;
        $data['status'] =$status;
        $data['updatetime'] =time();
        $res=ZhMatchmakerMeetModel::where(["id"=>$id])->update($data);
        if($res){
            //发起通知
            $notice["wxapp_id"]=$wxapp_id;
            $notice["u_id"]=0;//发送人id
            $notice['s_id'] =$matchmaker["u_id"];//接收人
            $notice['create_time'] =date("Y-m-d H:i:s");
            $notice['status'] =1;
            $c_id = ZhChat::insertGetId($notice);
            if($c_id){
                if($status==1){
                    $content="佳人/家长已同意您在".date("Y-m-d H:i:s",$matchmaker_meet["createtime"])."发起的“线下相亲邀请”";
                }elseif($status==2){
                    $content="佳人/家长已拒绝您在".date("Y-m-d H:i:s",$matchmaker_meet["createtime"])."发起的“线下相亲邀请”";
                }
                $log["wxapp_id"]=$wxapp_id;
                $log["chat_id"]=$c_id;
                $log["type"]="text";
                $log["content"]=$content;
                $log["add_time"]=date("Y-m-d H:i:s");
                $log["u_id"]=$matchmaker["u_id"];
                $log["is_read"]=0;
                $log["record_time"]=date("H:i",time());
                $c_log_id=ZhChatLog::insertGetId($log);
            }
            return $this->ajaxReturn($this->successCode, '操作成功');
        }else{
            return $this->ajaxReturn($this->errorCode, '操作失败');
        }
    }


}

